// accessid= '6MKOqxGiGU4AUk44';
// accesskey= 'ufu7nS8kS59awNihtjSonMETLI0KLy';
// host = 'http://post-test.oss-cn-hangzhou.aliyuncs.com';

accessid = '';
accesskey = '';
host = '';
policyBase64 = '';
signature = '';
callbackbody = '';
filename = '';
sendSuffix = '';
sendFilename = '';
key = '';
expire = 0;

g_dirname = ''
g_object_name = ''
g_object_name_type = 'local_name'
now = timestamp = Date.parse(new Date()) / 1000;
//文件id
fileId =0;
//文件时长
playTime =0;

var policyText = {
    "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
        ["content-length-range", 0, 1048576000] // 设置上传文件的大小限制
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {asBytes: true});
var signature = Crypto.util.bytesToBase64(bytes);

function send_request() {
    //if(fileId==0) {
        getFileId();
    //}
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
        var groupId= document.getElementById("groupId").value;
        serverUrl = '/oss/aliOssGetVideoPolicy?groupId='+groupId+"&name="+fileId+"&oldName="+encodeURI(sendFilename)+"&extName="+sendSuffix.substring(1)+"&playTime="+playTime;
        //console.log(serverUrl);
        xmlhttp.open("GET", serverUrl, false);
        xmlhttp.send(null);
        //console.log("responseText=" + xmlhttp.responseText)

        return xmlhttp.responseText
    }
    else {
        alert("Your browser does not support XMLHTTP.");
    }
};


function  getFileId() {
    var xmlhttp = null;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
        serverUrl = '/oss/getFileId';
        //console.log(serverUrl);
        xmlhttp.open("GET", serverUrl, false);
        xmlhttp.send(null);
        //console.log("responseText=" + xmlhttp.responseText)
        var responseText = xmlhttp.responseText;
        //console.log(JSON.stringify(responseText));
        var obj = eval("(" + responseText + ")");
        fileId=obj['id'];
        //console.log(obj['id']);
        return fileId;
    }
    else {
        alert("Your browser does not support XMLHTTP.");
    }
}

function get_signature() {
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    //now = timestamp = Date.parse(new Date()) / 1000;
    //if (expire < now + 3)
    //{
    body = send_request();
    //console.log(JSON.stringify(body))
    var obj = eval("(" + body + ")");
    policyBase64 = obj['policy'];
    host = obj['host'];
    accessid = obj['accessid'];
    signature = obj['signature'];
    expire = parseInt(obj['expire']);
    bucket = obj['bucket'];
    key = obj['dir'];
    callbackbody = obj['callback'];
    return true;
    //}
    //return false;
};

function check_object_radio() {
    g_object_name_type = 'random_name';
}

function get_dirname() {
    g_dirname = key
}



function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        g_object_name += "${filename}"
    }
    else if (g_object_name_type == 'random_name') {
        suffix = get_suffix(filename)
        g_object_name = g_dirname + fileId + suffix
    }
    return ''
}

function get_uploaded_object_name(filename) {
    if (g_object_name_type == 'local_name') {
        tmp_name = g_object_name
        tmp_name = tmp_name.replace("${filename}", filename);
        return tmp_name
    }
    else if (g_object_name_type == 'random_name') {
        return g_object_name
    }
}

function random_timestamp() {
    var timestamp = new Date().getTime();
    var pwd = '' + timestamp;
    var chars = '0123456789';
    var maxPos = chars.length;
    for (i = 0; i < 4; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}


function set_upload_param(up, filename, ret) {
    //console.log("filename=" + filename)
    sendSuffix = get_suffix(filename);
    sendFilename = filename.replace(sendSuffix, "");
    g_object_random_name = random_timestamp();
    if (ret == false)
    {
        ret = get_signature();
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename);
        calculate_object_name(filename);
    }

    //console.log(g_object_name, 1)
    new_multipart_params = {
        'key': g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid,
        'success_action_status': '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
        'callback': callbackbody,
    };

    //console.log(host, new_multipart_params)
    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}

/**
 * 获取时长
 * @param obj_file
 */
function getTimes(obj_file) {

    //获取录音时长
    var url = URL.createObjectURL(obj_file.getNative());
    var video = document.createElement("video");
    video.src= url;
    video.id = "video_"+obj_file.id;
    video.style.display = 'none';
    var duration=0;
    video.addEventListener("loadedmetadata", function (_event) {
        duration =parseInt(video.duration);
        $("#playTime-"+obj_file.id).text(duration)
        playTime = duration;
        //console.log(duration);
    });
}

var uploader = new plupload.Uploader({
    runtimes: 'html5,flash,silverlight,html4',
    browse_button: 'selectfiles',
    //multi_selection: false,
     container: document.getElementById('container'),
     flash_swf_url: '/public/oss/lib/plupload-2.1.2/js/Moxie.swf',
     silverlight_xap_url: '/public/oss/lib/plupload-2.1.2/js/Moxie.xap',
    url: 'http://oss.aliyuncs.com',

    filters: {
        mime_types : [ //只允许上传视频
            { title : "Video files", extensions : "mpg,m4v,mp4,flv,3gp,mov,avi,rmvb,mkv,wmv"},
        ],
        max_file_size : '200mb', //最大只能上传200mb的文件
        prevent_duplicates : true //不允许选取重复文件
    },

    init: {

        PostInit: function () {
            document.getElementById('postfiles').onclick = function() {
                if(uploader.files.length>0) {
                    $("button").each(function () {
                        $(this).attr("disabled","disabled");
                        $(this).addClass("layui-btn-disabled");
                    });
                    set_upload_param(uploader, '', false);
                    return false;
                    //console.log("PostInit", 1)
                }
            }
        },

        FilesAdded: function (up, files) {
            var demoListView = $('#test-upload-demoList')

            plupload.each(files, function(file) {

                var tr = $(['<tr id="upload-' + file.id + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + plupload.formatSize(file.size) +'</td>'
                    , '<td id="playTime-'+ file.id+'"></td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-mini test-upload-demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-mini layui-btn-danger test-upload-demo-delete" id="del-' + file.id + '">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //删除
                tr.find('.test-upload-demo-delete').bind('click', function (i) {
                    var del = $(this).attr("id");
                    var index = 0;
                    for(i=0;i<files.length;i++){
                        if(del.toString().split("-")[1]==files[i].id){
                            index =i;
                        }
                    }
                    uploader.removeFile(files[index]);
                    delete files[index]; //删除对应的文件
                    tr.remove();
                });

                demoListView.append(tr);
                //获取时长
                getTimes(file);
                //console.log("FilesAdded", 2)
            });
        },

        BeforeUpload: function (up, file) {
            //console.log("BeforeUpload", 3)
            check_object_radio();
            get_dirname();
            getTimes(file);
            set_upload_param(up, file.name, false);
        },

        UploadProgress: function (up, file) {
            var d= $("#upload-"+file.id);
            $(d.find("td")[3]).text(file.percent+"%");
        },

        FileUploaded: function (up, file, info) {
            //console.log("FileUploaded", 5);
            //console.log('upload to oss success, object name:' + get_uploaded_object_name(file.name) + ' 回调服务器返回的内容是:' + info.response);

        },

        Error: function (up, err) {
            //console.log("Error", 6);
            var code=err.code;
            var result ="";
            if(code==-602){
                result="您选择了重复的图片："+err.file.name;
            }else if(code==-601){
                result="您选择的视频类型不符合:"+err.file.name+"！目前支持：mpg,m4v,mp4,flv,3gp,mov,avi,rmvb,mkv,wmv格式";
            }else if(code==-600){
                result="您选择的视频太大:"+err.file.name+"！目前最大支持单次上传200MB视频";
            }
            $("#console").text(result);

        }
    }
});


uploader.init();